<template>
  <div id="companyRoles" class="route-page">
    <section v-if="roleLoading" class="text-center mt-50">
      <a-spin />
    </section>
    <a-card class="route-content" v-else>
      <a-layout class="layout" v-if="roleList.length" style="background: #fff">
        <a-layout-sider class="sider" :width="250" style="background: #fff">
          <div class="list">
            <a-list class="role-list" :data-source="roleList">
              <template #renderItem="{ item }">
                <a-list-item
                  class="list-item"
                  @click="handleRoleClick(item)"
                  :class="currentRole.id == item.id ? 'active' : ''"
                >
                  <a-list-item-meta class="flex align-center">
                    <template #title>
                      <span>{{ item.name }}</span>
                      <a-tag
                        v-if="item.is_system == 1"
                        class="ml-5"
                        color="purple"
                      >
                        系统角色
                      </a-tag>
                    </template>
                    <template #avatar>
                      <UserOutlined
                        style="margin-left: 10px; font-size: 18px"
                      />
                    </template>
                  </a-list-item-meta>
                  <template #actions>
                    <a-dropdown
                      :trigger="['click']"
                      @click.stop
                      v-if="item.is_system != 1"
                    >
                      <div class="text-right" style="width: 80px">
                        <MoreOutlined />
                      </div>
                      <template #overlay>
                        <a-menu>
                          <a-menu-item key="edit_role">
                            <a-button
                              type="link"
                              @click="handleRoleEdit(item.id)"
                            >
                              编辑角色
                            </a-button>
                          </a-menu-item>
                          <a-menu-item key="remove_role">
                            <a-button
                              type="link"
                              danger
                              @click="handleRoleDelete(item)"
                            >
                              删除角色
                            </a-button>
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </template>
                </a-list-item>
              </template>
            </a-list>
          </div>
          <div class="btns">
            <a-button
              class="w-100p"
              @click="handleRoleEdit()"
              type="primary"
              ghost
            >
              新增角色
            </a-button>
          </div>
        </a-layout-sider>
        <a-layout-content class="content">
          <section class="header">
            <span class="title">{{ currentRole.name }}</span>
            <TeamOutlined />
            <span class="ml-5"> {{ total }} </span>
            <a-space
              style="margin-left: 20px"
              v-if="currentRole.is_system != 1"
            >
              <a-button
                type="primary"
                ghost
                @click="handleRoleEdit(currentRole.id)"
              >
                编辑角色
              </a-button>
              <a-button
                type="danger"
                ghost
                @click="handleRoleDelete(currentRole)"
              >
                删除角色
              </a-button>
            </a-space>
          </section>
          <a-table
            class="user-table"
            :dataSource="userList"
            :columns="columns"
            :loading="userLoading"
            :pagination="pagination"
            @change="handleTableChange"
            :row-selection="userRowSelection"
            rowKey="uid"
          >
            <template #title>
              <section class="table-header">
                <a-input-search
                  v-model:value="userSearchVal"
                  placeholder="搜索成员姓名"
                  @search="onUserSearch"
                  :allowClear="true"
                  enter-button
                  style="width: 200px"
                />
                <section class="user-opt">
                  <a-button type="primary" class="mr-10" @click="addMembers()">
                    添加成员
                  </a-button>
                  <a-button
                    type="primary"
                    danger
                    :disabled="delMemberDiabled"
                    @click="removeMembers()"
                  >
                    移除成员
                  </a-button>
                </section>
              </section>
            </template>
            <template #bodyCell="{ text, record, index, column }">
              <template v-if="column.key === 'realname'">
                <a-space>
                  <span>{{ text }}</span>
                  <a-tag v-if="record.isCreator" color="cyan">创建人</a-tag>
                </a-space>
              </template>
              <template v-if="column.key === 'departmentLabel'">
                <a-tooltip>
                  <template #title>
                    <div v-for="(item, index) of text.labelTips" :key="index">
                      {{ index + 1 }}、{{ item }}
                    </div>
                  </template>
                  <span> {{ text.label }}</span>
                </a-tooltip>
              </template>
              <template v-if="column.key === 'action'">
                <!-- 创建者 -->
                <a-button
                  type="link"
                  v-if="record.isCreator && record.isSelf"
                  @click="changeCreator"
                >
                  转移
                </a-button>
                <!-- 1、所有人不能移除自己 2、超级管理员可以移除自己和创建者外所有人 3、其他角色可以移除除超级管理员外所有人  -->
                <a-button
                  type="link"
                  danger
                  v-else-if="
                    !record.isCreator &&
                    !record.isSelf &&
                    ($store.getters.userInfo.level == 99 ||
                      currentRole.is_system != 1)
                  "
                  @click="removeMembers(record)"
                >
                  移除
                </a-button>
                <span v-else>--</span>
              </template>
            </template>
          </a-table>
        </a-layout-content>
      </a-layout>
      <section v-else class="empty">
        <Empty
          :image="simpleImage"
          :imageStyle="{ width: '256px', height: '164px', margin: 'auto' }"
        >
          <template #description>
            <span> 您还没有创建角色，点击下方按钮快速创建角色~ </span>
          </template>
          <a-button type="primary" class="mt-20" @click="handleRoleEdit()">
            添加角色
          </a-button>
        </Empty>
      </section>
    </a-card>
    <edit-role
      :visible="roleEditVisible"
      @closeEdit="handleRoleEditClose"
      @success="handleRoleEditSuccess"
      :id="currentRoleId"
    ></edit-role>
    <ChooseOrgMember
      @request="$utils.commonRequest"
      :visible="addMemberVisible"
      :deptDisabled="true"
      :uMax="chooseMemberType == 'creator' ? 1 : -1"
      setUids="uncheck"
      :uids="selectedUids"
      :getDetail="chooseMemberType == 'creator'"
      @close="handleAddMemberClose"
      @success="handleAddMemberSuccess"
    />

    <!-- 转移机构创建者身份 -->
    <a-modal
      title="转移机构创建者身份"
      v-model:visible="changeCreatorVisible"
      centered
      :width="580"
      :confirmLoading="newCreatorLoading"
      @ok="changeCreatorSuccess"
    >
      <a-form>
        <a-alert
          show-icon
          message="过户成功后，您和过户后的账号需要重新登录才能生效哦~"
          style="margin-bottom: 20px"
        />
        <a-form-item label="转移给">
          <a-space size="large">
            <div v-if="newCreator && newCreator.uid">
              <a-avatar
                :src="newCreator.avatar"
                style="background-color: #1890ff"
              >
                <template #icon><UserOutlined /></template>
              </a-avatar>
              <span class="ml-5">{{ newCreator.realname }}</span>
            </div>
            <a-button type="primary" ghost @click="addMembers('creator')">
              {{ newCreator && newCreator.uid ? "更换成员" : "选择机构成员" }}
            </a-button>
          </a-space>
        </a-form-item>
        <a-form-item label="验证码" help="发送验证码至您的手机号码验证身份">
          <a-input-group compact style="width: 100%">
            <a-input
              placeholder="请输入验证码"
              style="width: 250px"
              type="number"
              v-model:value="phoneCode"
            />
            <a-button
              type="primary"
              ghost
              @click="sendSmsCode"
              :disabled="codeCount < 60"
            >
              {{
                codeCount < 60
                  ? `${codeCount}s后重新发送`
                  : sendCodeFlag
                  ? "重新发送"
                  : "发送验证码"
              }}
            </a-button>
          </a-input-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, watch, computed } from "vue";
import {
  UserOutlined,
  MoreOutlined,
  TeamOutlined,
} from "@ant-design/icons-vue";
import { Empty, message, Modal } from "ant-design-vue";
import EditRole from "./modules/EditRole.vue";
import { ChooseOrgMember } from "bl-common-vue3";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import store from "../../../store";

export default defineComponent({
  name: "orgRoleManage",
  components: {
    UserOutlined,
    MoreOutlined,
    TeamOutlined,
    Empty,
    EditRole,
    ChooseOrgMember,
  },
  setup() {
    // 转移创建者身份
    const changeCreatorVisible = ref(false);
    const newCreator = ref();
    const phoneCode = ref("");
    const codeCount = ref(60);
    const sendCodeFlag = ref(false);
    const newCreatorLoading = ref(false);
    let codeTimer = null;

    const changeCreator = () => {
      sendCodeFlag.value = false;
      newCreatorLoading.value = false;
      if (codeTimer) {
        clearInterval(codeTimer);
        codeTimer = null;
        codeCount.value = 60;
      }
      changeCreatorVisible.value = true;
    };

    const sendSmsCode = () => {
      request.post("/message", "/sms/sendSmsCode/org").then((res) => {
        message.success("验证码发送成功，请注意查收~");
        sendCodeFlag.value = true;
        codeCount.value--;
        codeTimer = setInterval(() => {
          codeCount.value--;
          if (codeCount.value == 0) {
            clearInterval(codeTimer);
            codeTimer = null;
            codeCount.value = 60;
          }
        }, 1000);
      });
    };

    const changeCreatorSuccess = () => {
      if (!newCreator.value || !newCreator.value.uid) {
        message.warning("请选择转交用户对象！");
        return;
      }
      if (!phoneCode.value) {
        message.warning("请输入手机验证码！");
        return;
      }
      newCreatorLoading.value = true;
      request
        .post("/org", "/org/creator/change", {
          code: phoneCode.value,
          admin_uid: newCreator.value.uid,
        })
        .then(() => {
          changeCreatorVisible.value = false;
          store.dispatch("Logout");
        })
        .finally(() => {
          newCreatorLoading.value = false;
        });
    };

    const roleLoading = ref(true);
    // 角色列表
    const roleList = ref([]);
    // 当前选中的角色
    const currentRole = ref({});
    // 当前操作的角色id
    const currentRoleId = ref();
    // 编辑\添加角色抽屉显隐
    const roleEditVisible = ref(false);
    // 用户列表
    const userList = ref([]);
    // 搜索用户
    const userSearchVal = ref("");

    // 点击角色
    const handleRoleClick = (role) => {
      currentRole.value = role;
      page.value = 1;
      getUserList();
    };

    // 编辑\添加角色打开
    const handleRoleEdit = (id) => {
      currentRoleId.value = id;
      roleEditVisible.value = true;
    };
    // 编辑\添加角色关闭
    const handleRoleEditClose = () => {
      roleEditVisible.value = false;
    };
    // 角色编辑\添加成功
    const handleRoleEditSuccess = () => {
      successCallBack();
      handleRoleEditClose();
    };
    // 删除角色
    const handleRoleDelete = (role) => {
      if (Number(role.user_total) > 0) {
        Modal.warning({
          title: () => "提示",
          content: () => `删除“${role.name}”角色前请先移除该角色下的所有成员！`,
          centered: true,
        });
        return;
      }
      utils.modalConfirm({
        title: "提示",
        content: `确认删除角色“${role.name}”吗？`,
        okType: "danger",
        centered: true,
        onOk: () => {
          request
            .del("/org", "/department/role", {
              role_id: role.id,
              needMsg: true,
            })
            .then((res) => {
              message.success(res.msg || "删除成功！");
              successCallBack();
            });
        },
      });
    };
    // 操作成功后的回调
    const successCallBack = () => {
      getRoleList();
    };

    // 获取角色列表
    const getRoleList = () => {
      request
        .get("/org", "/department/role")
        .then((res) => {
          roleList.value = res.list || [];
          if (roleList.value.length) {
            let index = 0;
            if (Object.keys(currentRole.value).length) {
              index = roleList.value.findIndex(
                (item) => item.id == currentRole.value.id
              );
            }
            if (index < 1) {
              currentRole.value = roleList.value[0];
            }
            getUserList();
          }
        })
        .finally(() => {
          roleLoading.value = false;
        });
    };

    // 获取角色下的用户列表
    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const userLoading = ref(false);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));
    const handleTableChange = (pager) => {
      page.value = pager.current;
      limit.value = pager.pageSize;
    };
    const getUserList = () => {
      userLoading.value = true;
      request
        .get("/org", "/role/userList", {
          page: page.value,
          limit: limit.value,
          keyword: userSearchVal.value,
          role_id: currentRole.value.id,
        })
        .then((res) => {
          userList.value = res.list || [];
          total.value = res.total;
        })
        .finally(() => {
          userLoading.value = false;
        });
    };
    watch(pagination, () => {
      getUserList();
    });
    const userSelectedKeys = ref([]);
    const userRowSelection = {
      onChange: (selectedRowKeys) => {
        userSelectedKeys.value = selectedRowKeys;
      },
      getCheckboxProps: (record) => ({
        disabled: record.isCreator,
        name: record.name,
      }),
    };
    const delMemberDiabled = computed(() => {
      return userSelectedKeys.value.length ? false : true;
    });

    // 搜索用户
    const onUserSearch = () => {
      page.value = 1;
      getUserList();
    };

    // 添加成员
    const addMemberVisible = ref(false);
    const chooseMemberType = ref("add");
    const selectedUids = ref([]);
    const addMembers = (type = "add") => {
      chooseMemberType.value = type;
      if (type == "add") {
        request
          .get("/org", "/role/getOtherUser", { role_id: currentRole.value.id })
          .then((res) => {
            selectedUids.value = res.data;
            selectedUids.value.push(store.getters.userInfo.admin_uid);
            addMemberVisible.value = true;
          });
      } else {
        selectedUids.value = [store.getters.userInfo.admin_uid];
        addMemberVisible.value = true;
      }
    };
    const handleAddMemberClose = () => {
      addMemberVisible.value = false;
      chooseMemberType.value = "";
    };
    const handleAddMemberSuccess = (data) => {
      const { user } = data;
      // 添加用户至选中角色
      if (user && user.length) {
        if (chooseMemberType.value == "add") {
          request
            .post("/org", "/role/bindUser", {
              uids: user.join(","),
              role_id: currentRole.value.id,
              needMsg: true,
            })
            .then((res) => {
              message.success(res.msg || "添加成功！");
              addMemberVisible.value = false;
              page.value = 1;
              getRoleList();
            });
        } else {
          newCreator.value = user[0];
          addMemberVisible.value = false;
        }
      }
    };

    // 移除成员
    const removeMembers = (current) => {
      const content = current
        ? `确认移除成员“${current.realname}”的${currentRole.value.name}身份吗?`
        : `确认移除角色「${currentRole.value.name}」下选中的成员吗?`;
      utils.modalConfirm({
        title: "提示",
        content,
        okType: "danger",
        centered: true,
        onOk: () => {
          request
            .del("/org", "/role/unbindUser", {
              role_id: currentRole.value.id,
              uids: current ? current.uid : userSelectedKeys.value.join(","),
              needMsg: true,
            })
            .then((res) => {
              message.success(res.msg || "移除成功！");
              userSelectedKeys.value = [];
              page.value = 1;
              getRoleList();
            });
        },
      });
    };

    const init = () => {
      getRoleList();
    };

    init();
    return {
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      roleLoading,
      roleList,
      currentRole,
      currentRoleId,
      roleEditVisible,
      columns,
      userList,
      userSearchVal,
      userLoading,
      pagination,
      addMemberVisible,
      total,
      userRowSelection,
      delMemberDiabled,
      selectedUids,
      handleRoleEdit,
      handleRoleClick,
      handleRoleEditClose,
      handleRoleEditSuccess,
      handleRoleDelete,
      onUserSearch,
      handleTableChange,
      addMembers,
      handleAddMemberClose,
      handleAddMemberSuccess,
      removeMembers,
      chooseMemberType,
      newCreator,
      changeCreatorVisible,
      sendSmsCode,
      changeCreatorSuccess,
      codeCount,
      phoneCode,
      sendCodeFlag,
      changeCreator,
      newCreatorLoading,
    };
  },
});

const columns = [
  { title: "姓名", dataIndex: "realname", key: "realname" },
  { title: "电话", dataIndex: "phone" },
  { title: "工号", dataIndex: "job_number" },
  {
    title: "所属部门",
    dataIndex: "departmentLabel",
    key: "departmentLabel",
  },
  {
    title: "操作",
    dataIndex: "uid",
    key: "action",
  },
];
</script>

<style lang="less" scoped>
#companyRoles {
  &:deep(.layout) {
    background: #fff;
  }
  &:deep(.ant-card-body) {
    height: 100%;
  }
  .layout {
    height: 100%;
    .sider {
      height: 100%;
      position: relative;
      .list {
        padding: 10px 0px 70px 0;
        height: 100%;
        overflow-y: auto;
        overflow-x: hidden;
        box-sizing: border-box;
        .role-list {
          &:deep(.ant-list-item-meta) {
            align-items: center;
          }
          &:deep(.ant-list-item-action) {
            margin-left: 0px;
          }
          &:deep(.ant-list-item) {
            border-bottom: none;
          }
          .list-item {
            cursor: pointer;
            padding: 8px !important;
          }
          .active {
            background: @primary-color-bg;
            color: @primary-color;
            &:deep(.ant-list-item-meta-title) {
              color: @primary-color;
            }
          }
        }
      }
      .btns {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 40px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: #fff;
        z-index: 99;
      }
    }
    .content {
      height: 100%;
      background: #fff;
      padding: 0 20px;
      border-left: 1px solid #f4f4f4;
      margin-left: 20px;
      .header {
        height: 50px;
        display: flex;
        align-items: center;
        position: relative;
        padding-left: 15px;
        font-size: 16px;
        color: rgba(0, 0, 0, 0.5);
        &::before {
          position: absolute;
          left: 0px;
          top: 12px;
          bottom: 12px;
          width: 4px;
          background: @primary-color;
          content: "";
        }
        .title {
          font-size: 18px;
          color: rgba(0, 0, 0, 0.8);
          margin-right: 10px;
        }
      }
      .user-table {
        .table-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
      }
    }
  }
  .empty {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    &:deep(.ant-empty-img-simple) {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
